--- 模块功能：播放拨号音功能
-- @author miuser
-- @module elderphone.hookdetect
-- @license MIT
-- @copyright miuser
-- @release 2020-05-15

module(...,package.seeall)
--摘机电压范围
local off_hook_voltage={0,250}
--挂机电压范围
local on_hook_voltage={350,1200}

--1挂机，0摘机
local on_hook=-1

--正在拨号
local plate_moving=0

--正在响铃
local ringing=0

--峰值电压
local sumVoltage=-1
local sampleCount=0

local function pub(s)
    sys.publish(s)
end

local function uar(s)
    sys.publish("UARTOUT",s)
end

--- ADC2读取
local function read2()
    --ADC1接口用来读取电压
    local ADC_ID = 2
    -- 读取adc
    -- adcval为number类型，表示adc的原始值，无效值为0xFFFF
    -- voltval为number类型，表示转换后的电压值，单位为毫伏，无效值为0xFFFF；adc.read接口返回的voltval放大了3倍，所以需要除以3还原成原始电压
    local adcval,voltval = adc.read(ADC_ID)
    --log.info("testAdc2.read",voltval)
    sumVoltage=sumVoltage+voltval
    sampleCount=sampleCount+1

    if (sampleCount>=10) then
        --log.info("elderphone.hookdetect","maxvol",sumVoltage)
        --sys.publish("UARTOUT",sumVoltage)
        local last_on_hook=on_hook
        local voltage=sumVoltage/10
        log.info("ADC.read",voltage)
        if voltage>off_hook_voltage[1] and voltage<off_hook_voltage[2] then on_hook=0 end
        if voltage>on_hook_voltage[1] and voltage<on_hook_voltage[2] then on_hook=1 end
        --log.info("on_hook=",on_hook)
        --log.info("plate_moving=",plate_moving)
        --log.info("elderphone.hookdetect","plate_moving",plate_moving)
        if plate_moving==0 then
            --log.info("elderphone.hookdetect","onhook",on_hook)
            if (on_hook~=last_on_hook) and (on_hook==0) then
                pub("OFF_HOOK")
                uar("摘机")
            end
            if (on_hook~=last_on_hook) and (on_hook==1) then
                pub("ON_HOOK")
                uar("挂机")
            end
        end
        sampleCount=0
        sumVoltage=0
    end
end

-- 开启对应的adc通道
adc.open(2)

-- 定时每秒读取adc值
sys.timerLoopStart(read2,5)



local function plateMoving()
    plate_moving=1
    log.info("elderphone.hookdetect","plate_moving=",plate_moving)
end
sys.subscribe("PLATE_MOVING", plateMoving)
local function plateStop()
    plate_moving=0
    log.info("elderphone.hookdetect","plate_moving=",plate_moving)

end
sys.subscribe("PLATE_STOP", plateStop, 100)


local function ringing_start()
    ringing=1
end
sys.subscribe("AMARMING", ringing_start)
local function ringing_stop()
    ringing=0
end
sys.subscribe("AMARMING_OFF", ringing_stop)